//
// Created by gj on 16-2-20.
//

#ifndef ALLUTILS_CMUTEX_H
#define ALLUTILS_CMUTEX_H

#include "../log/CLog.h"

#include <pthread.h>

class MutexAttr {
public:
    MutexAttr() {
        pthread_mutexattr_init(&p_mutex_attr);
    }

    virtual ~MutexAttr() {
        pthread_mutexattr_destroy(&p_mutex_attr);
    }

private:
    pthread_mutexattr_t p_mutex_attr;

    friend class CMutex;
};

class CMutex {
public:
    CMutex() {
        __create_mutex(NULL);
    }

    CMutex(MutexAttr &attr) {
        __create_mutex(&attr);
    }

    int lock() {
        return pthread_mutex_lock(&p_mutex);
    }

    int unlock() {
        return pthread_mutex_unlock(&p_mutex);
    }

    int trylock() {
        return pthread_mutex_trylock(&p_mutex);
    }

    virtual ~CMutex() {
        pthread_mutex_destroy(&p_mutex);
    }

private:
    pthread_mutex_t p_mutex;

    void __create_mutex(MutexAttr *);
};

class AutoMutex {
public:
    AutoMutex(CMutex &mutex) //
            : mutex(&mutex) {
        lock();
    }

    AutoMutex(CMutex *mutex) //
            : mutex(mutex) {
        lock();
    }

    virtual ~AutoMutex() {
        mutex->unlock();
    }

private:
    CMutex *mutex;

    void lock() {
        mutex->lock();
    }
};

#include "ThreadSharePointer.h"

#endif //ALLUTILS_CMUTEX_H
